// leave.js
import { uploadCase, reviewLeave, download } from '../../assest/api.js'
import { parseJson2Query } from '../../assest/utils.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user : '',
    banners: {
      template: 'first',
      one: 'action',
      two: 'disabled',
      three: 'disabled'
    },
		first: {
      hiddenUpload: true, //隐藏病例上传按钮
      hiddenPreview: true,
      hiddenTimepicker: true, //隐藏时间选择器
      hasTap: false,
      types: ['事假', '病假'],
      picker: '选择请假类型(病假需提供相关证明)',//类型
      fromTime: '选择请假开始时间',
      endTime: '选择请假结束时间',
			clazz: '',//班级
      filePath: '',//文件路径
      whichTime: '',//被选择的时间
      time: {
        inputFromTime: '',
        inputEndTime: '',
        times: '',
        current: '',
        years: new Date().getFullYear(),
        months: '',
        days: '',
        course: [12, 34, 56, 78]
      }
		},
    second: {
      navItemHover: ['nav-item-hover'], //默认点击效果
      waitRe:[], //等待审核
      hasRe:[], //已通过审核
      cancelRe:[], //未通过审核
      render:[], //实际渲染数据
    }
  },
  /* 学生请假申请页面 */
  choseTimepicker: function (e){
    const whicheTime = this.data.first.whichTime
    const times = this.data.first.time.times.split('-')
    const time_cn = times[0] + '年' + times[1] + '月'
                  + times[2] + '日' + times[3] + '节'
    if(whicheTime === 'from'){
      this.setData({ 'first.fromTime': time_cn})
      this.setData({ 'first.time.inputFromTime': this.data.first.time.times })
    }
    else{
      this.setData({ 'first.endTime': time_cn })
      this.setData({ 'first.time.inputEndTime': this.data.first.time.times })
    }
  
    this.setData({ 'first.hiddenTimepicker': true })
  },
  showTimepicker: function(e){
    let show = this.data.first.hiddenTimepicker ? false : true
    
    this.setData({ 'first.whichTime': e.target.id })
    this.setData({'first.hiddenTimepicker': show})
  },
  typeChange: function({detail}) {
    let index = detail.value
    let first = this.data.first
    first.picker = first.types[index]
    
    if (index === '1'){
      first.hiddenUpload = false
    } else {
      first.hiddenUpload = true
      first.hiddenPreview= true
      first.filePath = ''
    }
    this.setData({ first: first })
  },
  upload: function(e) {
    const _this = this
    wx.chooseImage({
      success: function(res) {
        _this.setData({ 'first.filePath': res.tempFilePaths[0]})
        wx.previewImage({
          urls: res.tempFilePaths,
          success: () =>{
            _this.setData({ 'first.hiddenPreview': false})
            wx.showModal({
              title: '提示',
              content: '病例上传完成, 若病例图片选择错误, 重新选择上传即可',
              showCancel: false,
              confirmText: '知道了'
            })
          }
        })
      },
    })
  },
  preview: function(e){
    const _this = this
    wx.previewImage({
      urls: [_this.data.first.filePath],
    })
  },
  timeChange: function ({target, detail}){
    const time = this.data.first.time
    const month = time.months[detail.value[1]];
    if (month !== time.current){
      let days = []
      for (let i = 1; i <= new Date(time.years, month, 0).getDate(); i++) {
        days.push(i)
    }
      this.setData({ 'first.time.current': month })
      this.setData({ 'first.time.days': days })
    }
    const index = detail.value
    let times = time.years + '-' + time.months[index[1]] + '-'
              + time.days[index[2]] + '-' + time.course[index[3]]

    this.setData({ 'first.time.times': times })
  },
  submit: function({detail}) {
    let gate = true
    Object.values(detail.value).forEach((v) => {
      if(v === '') gate = false
    })
    if (gate){
      this.setData({ 'first.hasTap': gate })
      wx.showLoading({
        title: '正在提交申请...',
        mask: true
      })
      
      let _this = this
      detail.value.s_id = this.data.user.id
      detail.value.t_version = 0
      uploadCase(detail.value, this.data.first.filePath, ({ statusCode }) => {
        if (statusCode === 200){
          // let banners = _this.banners.two
          // _this.setData({ banners: banners})
          wx.navigateBack({
            delta: 1
          })
        }
        wx.hideLoading()
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '请认真填写所有的内容',
        showCancel: false
      })
    }
  },
  /* 学生请假申请页面 */

  /* review页面 */
  navTap: function (e){
    let index = Number(e.target.dataset.index)
    let navItemHover = new Array()
    navItemHover[index] = 'nav-item-hover'
    this.setData({ 'second.navItemHover': navItemHover})

    let render = e.target.dataset.render
    this.setData({ 'second.render': this.data.second[render] })

  },
  seeDetail: function ({currentTarget}){
    const index = currentTarget.dataset.index
    const query = parseJson2Query(this.data.second.render[index])
    wx.navigateTo({
      url: `detail/detail?${query}`,
    })
  },
  seeCase: ({currentTarget}) => {
    const pic = currentTarget.dataset.pic
    wx.previewImage({
      urls: [pic],
    })
    
  },
  /* review页面 */

  /*下载假条 */
  download: function ({detail}){
    const id = detail.target.dataset.id
    const email = detail.value.email
    const days = this.data.detail.days
    const clazz = this.data.detail.clazz
    wx.showModal({
      title: '温馨提示',
      content: '您在下载假条的时候,已经承诺以上请假情况属实，并已告知家长。请假期间能够保证个人人身安全，如弄虚作假出现一切后果，由个人承担，并接受相应的校纪校规处分。',
      success: ({confirm, cancel}) => {
        if(confirm){
          wx.showLoading({
            title: '正在生成假条',
            mask: true
          })
          
          const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
          if (email === '' || !reg.test(email)){
            wx.showToast({
              title: '请正确的输入邮箱',
              icon: 'image',
              image: '../../assest/img/error.png',
              duration: 2000,
              mask: true
            })
          } else{
            download({ id, email, days, clazz}, ({savedFilePath}) => {
              wx, wx.hideLoading()
              wx.showModal({
                title: '提醒',
                content: `假条已发送到你的邮箱中, 请打印后交至教育大楼1816`,
                showCancel: false,
                confirmText: '知道了'
              })
            })
          }
          
        }
      }
    })
  },
  /*下载假条 */

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const user = wx.getStorageSync('user')
    const banner = options.banner

    if (banner){
      let start = options.from.replace(/[^0-9]/ig, ",").split(",")
      let end = options.end.replace(/[^0-9]/ig, ",").split(",")
      options.days = (end[0] - start[0]) * 365
        + (end[1] - start[1]) * 30
        + (end[2] - start[2]) + 1

      if (banner && banner === 'two') {
        this.setData({ banners: this.banners.two })
      }
      if (banner && banner === 'three') {
        this.setData({ banners: this.banners.three })
      }
    }

    this.setData({user: user})
    this.setData({detail: options})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const user = this.data.user
    const _this = this

    if (user.role === 0) {
      const user = this.data.user

      const date = new Date()
      let first = this.data.first

      let num = user.studentId
      let clazz = num.substr(2, 2) + num.substr(9, 2)
      first.clazz = clazz

      let time = first.time
      time.current = date.getMonth() + 1
      let months = []
      let days = []
      let course = []
      for (let i = time.current; i <= 12; i++) {
        months.push(i)
      }
      time.months = months
      for (let i = date.getDate();
        i <= new Date(time.years, time.current, 0).getDate();
        i++) {
        days.push(i)
      }
      time.days = days

      first.time = time

      let times = time.years + '-' + time.months[0] + '-'
        + time.days[0] + '-' + time.course[0]

      this.setData({ 'first.time.times': times })

      this.setData({ first: first })
     
    } else if (user.role === 1) {
      reviewLeave(user, ({data}) => {
        let second = _this.data.second
        second.waitRe = []
        second.hasRe = []
        second.cancelRe = []

        Object.values(data).forEach((v) => {

          let start = v.from.split('-')
          v.from = start[0] + '年' + start[1] + '月'
            + start[2] + '日 ' + start[3] + '节'
          let end = v.end.split('-')
          v.end = end[0] + '年' + end[1] + '月'
            + end[2] + '日 ' + end[3] + '节'

          v.reason_s = v.reason.length <= 13 ?
            v.reason :
            v.reason.substr(0, 15) + '....'

          switch (v.t_version) {
            case 0: second.waitRe.push(v); break;
            case 1: second.hasRe.push(v); break;
            case 2: second.cancelRe.push(v); break;
          }
        })

        switch (second.navItemHover.length){
          case 1: second.render = second.waitRe; break;
          case 2: second.render = second.hasRe; break;
          case 3: second.render = second.cancelRe; break;
        }

        _this.setData({ second: second })

      })
    } else if (user.role === 2) {
      reviewLeave(user, ({data}) => {
        let second = _this.data.second
        second.waitRe = []
        second.hasRe = []
        second.cancelRe = []

        Object.values(data).forEach((v) => {

          let start = v.from.split('-')
          v.from = start[0] + '年' + start[1] + '月'
            + start[2] + '日 ' + start[3] + '节'
          let end = v.end.split('-')
          v.end = end[0] + '年' + end[1] + '月'
            + end[2] + '日 ' + end[3] + '节'

          v.reason_s = v.reason.length <= 13 ?
            v.reason :
            v.reason.substr(0, 15) + '....'

          switch (v.l_version) {
            case 0: second.waitRe.push(v); break;
            case 1: second.hasRe.push(v); break;
            case 2: second.cancelRe.push(v); break;
          }
        })

        switch (second.navItemHover.length) {
          case 1: second.render = second.waitRe; break;
          case 2: second.render = second.hasRe; break;
          case 3: second.render = second.cancelRe; break;
        }

        _this.setData({ second: second })

      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  banners: {
    two: {
      template: 'second',
      one: '',
      two: 'action',
      three: 'disabled'
    },
    three: {
      template: 'second',
      one: '',
      two: '',
      three: 'action'
    }
  }
})